import { Alert, PermissionsAndroid } from 'react-native';
import Geolocation from 'react-native-geolocation-service';
import LaunchNavigator from 'react-native-launch-navigator';
import Toast from 'react-native-toast-message';

interface ILocation {
  latitude: number;
  longitude: number;
}
class LocationClass {
  /**
   * 是否有定位许可
   */
  public static async hasLocationPermission() {
    const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, {
      title: '位置权限请求',
      message: '为提供更多的服务，APP将获取您的位置信息',
      buttonNeutral: '稍后问我',
      buttonNegative: '拒绝',
      buttonPositive: '提供位置',
    });

    return granted === PermissionsAndroid.RESULTS.GRANTED;
  }

  /**
   * 获取定位信息
   */
  public static async getLocation(): Promise<Geolocation.GeoPosition> {
    const hasPermission = await this.hasLocationPermission();
    if (!hasPermission) {
      Alert.alert('为提供更多的服务，APP将获取您的位置信息，请打开位置权限');
      return Promise.reject(null);
    }
    return new Promise((resolve, reject) => {
      Geolocation.getCurrentPosition(
        (res) => {
          const position: Geolocation.GeoPosition = res;
          resolve(position);
        },
        (error) => {
          console.error(error);
          reject(error);
        },
        { enableHighAccuracy: true },
      );
    });
  }

  /**
   * 打开百度地图APP 进行导航
   * @param location
   * @param destinationName
   * @param appName
   */
  public static async openSystemNavigation(location: ILocation, destinationName: string, appName: string = 'baidu') {
    const AvailableApps = await LaunchNavigator.getAvailableApps();
    if (!AvailableApps || !AvailableApps[appName]) {
      Toast.show({ type: 'error', text1: '导航错误: 请先安装百度地图' });
      return;
    }
    const isAvailable = LaunchNavigator.isAppAvailable(appName);
    if (isAvailable) {
      LaunchNavigator.navigate([location.latitude, location.longitude], {
        app: appName,
        destinationName,
      }).catch((error) => {
        Toast.show({ type: 'error', text1: '导航错误: ' + error });
      });
    } else {
      Toast.show({ type: 'error', text1: '导航不可用，请重装导航地图' });
    }
  }
}

export default LocationClass;
